/*
		ServEngine framework library
		A library to fast develop JEE online applications
	
		Copyright 2008 José Ignacio de Córdoba Álvaro

		Licensed under the Apache License, Version 2.0 (the "License");
		you may not use this file except in compliance with the License.
		You may obtain a copy of the License at

				http://www.apache.org/licenses/LICENSE-2.0

		Unless required by applicable law or agreed to in writing, software
		distributed under the License is distributed on an "AS IS" BASIS,
		WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
		See the License for the specific language governing permissions and
		limitations under the License.
	
		Jose Ignacio de Cordoba Alvaro
		http://ignacio.decordoba.com
*/

package com.servengine.log;

import com.servengine.struts.AdminServiceAction;
import com.servengine.struts.ClientAction;
import com.servengine.user.UserSessionSBean;

import java.io.BufferedWriter;
import java.io.IOException;

import java.util.TreeSet;

import javax.naming.Context;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class AdminActions extends ClientAction implements AdminServiceAction
{
	private static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(Actions.class.getName() );
	LogManagerLocal logManager;

	protected void initAction(Context initialcontext)
	{
		try
		{
			logManager = (LogManagerLocal)initialcontext.lookup("LogManager/local");
		} catch (Throwable e)
		{
			throw new IllegalStateException(e.getMessage(),e);
		}
		log.info(getClass().getName()+" initialized");
	}
	public ActionForward getEntries(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException
	{
		try
		{
			UserSessionSBean userSession = getUserSession(request);
			LogEntriesActionForm entriesForm = (LogEntriesActionForm)form;
		  if (log.isDebugEnabled())
				log.debug(userSession.getPortalid()+","+entriesForm.getUserId()+","+entriesForm.getModule()+","+entriesForm.getAction()+","+entriesForm.getMethodName()+","+entriesForm.getFrom()+","+entriesForm.getTo());
			TreeSet<LogEntry> entries = new TreeSet<LogEntry>();
			entries.addAll(logManager.getEntries(userSession.getPortalid(),entriesForm.getUserId(),entriesForm.getModule(),entriesForm.getAction(),entriesForm.getMethodName(), entriesForm.getFrom().getTime(), entriesForm.getTo().getTime(), entriesForm.getData(), entriesForm.getMaxResults()));
			String[] fieldNames = entriesForm.getFields()==null?new String[0]:entriesForm.getFields().split(",");
		  response.setContentType("text/plain"); 
		  response.setHeader("Content-disposition", "attachment;filename="+userSession.getPortalid()+"_"+entriesForm.getModule()+"_"+entriesForm.getAction()+"_"+entriesForm.getMethodName()+".txt");     
		  BufferedWriter writer = new BufferedWriter(response.getWriter());
			for (LogEntry entry: entries)
			{
				if (entriesForm.getFields()==null || entriesForm.getFields().length()==0)
					writer.write(userSession.getPortalid()+","+(entry.getUserId()==null?"":""+entry.getUserId())+","+
						(entry.getModule()==null?"":entry.getModule())+","+(entry.getAction()==null?"":entry.getAction())+","+(entry.getMethodName()==null?"":entry.getMethodName())+","+(entry.getData()==null?"":entry.getData())+","+entry.getDate()+","+entry.getIpaddress());
				else
					for (int i=0; i<fieldNames.length; i++)
					{
						if (fieldNames[i].equals("portalid"))
							writer.write(userSession.getPortalid());
						else if (fieldNames[i].equals("userId"))
							writer.write(entry.getUserId()==null?"":""+entry.getUserId());
						else if (fieldNames[i].equals("module"))
							writer.write(entry.getModule()==null?"":entry.getModule());
						else if (fieldNames[i].equals("action"))
							writer.write(entry.getAction()==null?"":entry.getAction());
						else if (fieldNames[i].equals("methodName"))
							writer.write(entry.getMethodName()==null?"":entry.getMethodName());
						else if (fieldNames[i].equals("data"))
							writer.write(entry.getData()==null?"":entry.getData());
						else if (fieldNames[i].equals("date"))
							writer.write(entry.getDate()==null?"":""+entry.getDate());
						else if (fieldNames[i].equals("ipaddress"))
							writer.write(entry.getIpaddress()==null?"":entry.getIpaddress());
						if (i<fieldNames.length-1)
							writer.write(",");
					}
				writer.newLine();
			}
			writer.close();
			return null;
		} catch (Throwable e)
		{
			log.error(e.getMessage(),e);
			saveErrors(request,getErrorsFromException(e));
			return mapping.findForward("error");
		}
	}
}
